import KoaRouter from 'koa-router'
import Config from '@/config/Config'
import verifyToken from '@/middlewares/verifyToken'
import { Models } from '@/common/typings/modle'
import { command } from '@/server/mysql'
import { HttpException, Success } from '@/core/HttpException'
import { addUpdate, getUpdateContent } from '@/common/utils/sql'
import validator from '@/middlewares/validator'
import schema from '@/common/api-json-schema/system/common/update'
import { formatUpdateMsg } from '@/common/utils/formatMsg'
const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v1/system/role`,
})
router.post('/update', verifyToken, validator(schema, 'body'), async (ctx: Models.Ctx) => {
  const { roleName, roleCode, resourceList, userList, status, id, updateStatusOnly = false } = ctx.request.body as any
  const fieldObj = {
    roleName,
    roleCode,
    status,
  }
  const result = (
    await command(
      addUpdate(`UPDATE system_role SET ${getUpdateContent(fieldObj)} WHERE id = '${id}'
 ;`),
      true,
    )
  ).results
  if (result.affectedRows === 1) {
    if (!updateStatusOnly) {
      // 全部删除关联关系
      await command(`DELETE FROM system_role_resource WHERE role_id = '${id}';`)
      await command(`DELETE FROM system_user_role WHERE role_id = '${id}';`)
      // 全部插入
      const insertResourceSql = resourceList
        .map(
          (resourceId: any) =>
            `INSERT INTO system_role_resource (role_id, resource_id) values ('${id}', '${resourceId}');`,
        )
        .join('')
      const insertUserSql = userList
        .map((userId: any) => `INSERT INTO system_user_role (role_id, user_id) values ('${id}', '${userId}');`)
        .join('')
      ;(await command(`${insertResourceSql}${insertUserSql}`)).results
    }
    throw new Success({ data: result, msg: formatUpdateMsg(status, updateStatusOnly) })
  }
  throw new HttpException()
})
export default router
